/*
	Connection对象的query方法返回对象使用示例
*/

var mysql = require('mysql');
var fs = require('fs');

var connection = mysql.createConnection({
	host: 'localhost',
	port: 3306,
	database: 'test',
	user: 'root',
	password: '123456'
});

var out = fs.createWriteStream('./message.txt');

out.on('error', function(err){
	console.log("写文件操作失败，错误信息为：" + err.message);
	process.exit();
});

connection.connect(function(err){
	if(err)
		console.log("连接失败");
	else{
		console.log("连接成功");

		// Connection对象的query方法返回一个可用于处理流数据的对象，如要使用这个对象，在query方法中不能使用callback
		var query = connection.query('select * from users');

		query
		.on('error', function(err){
			console.log("读取数据失败，错误信息为：" + err.message);
			process.exit();
		})

		.on('fields', function(fields){
			var str = "";
			fields.forEach(function(field){
				if(str != "")
					str += String.fromCharCode(9);
				str += field.name;
			});
			out.write(str + '\r\n');
		})

		.on('result', function(row){
			connection.pause();
			out.write(row.id + String.fromCharCode(9) + row.userName + String.fromCharCode(9) + row.passWord + '\r\n', function(err){
				connection.resume();
			});
		})

		.on('end', function(){
			console.log("数据全部写入完毕");
			connection.end();
		});
	}
});